package com.walkline.screen;

import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.util.sqlite.Card;
import com.walkline.util.sqlite.SQLManager;
import com.walkline.util.ui.ForegroundManager;

public class SettingsCardScreen extends MainScreen
{
	private SQLManager _sqlManager;
	private ForegroundManager _foreground = new ForegroundManager(0);

	private ObjectChoiceField _choiceCardID;
	private EditField _bankName;
	private EditField _tailNumber;
	private DateField _accountsDay;
	private DateField _repaymentDay;
	private EditField _phoneNumber;

	public SettingsCardScreen(SQLManager sqlManager)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		setTitle("Card Settings");

		_sqlManager = sqlManager;

		_choiceCardID = new ObjectChoiceField("IDs: ", null, 0) {
			protected void fieldChangeNotify(int context)
			{
				if (context != FieldChangeListener.PROGRAMMATIC)
				{
					queryFirstRecorderDetails();
				}
			};
		};
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		_bankName = new EditField("Bank name: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);
		_tailNumber = new EditField("Tail number: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);
		_accountsDay = new DateField("Accounts day: ", 0, sdf);
		_repaymentDay = new DateField("Repayment day: ", 0, sdf);
		_phoneNumber = new EditField("Phone number: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);

		_foreground.add(_choiceCardID);
		_foreground.add(_bankName);
		_foreground.add(_tailNumber);
		_foreground.add(_accountsDay);
		_foreground.add(_repaymentDay);
		_foreground.add(_phoneNumber);
        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run()
			{
				String[] _cards = _sqlManager.getCardListsID();
				_choiceCardID.setChoices(_cards);

				queryFirstRecorderDetails();
			}
		});
	}

	private void queryFirstRecorderDetails()
	{
		String currentID = _choiceCardID.getChoice(_choiceCardID.getSelectedIndex()).toString();

		if (!currentID.equalsIgnoreCase("none"))
		{
			Card card = _sqlManager.getCardByID(Integer.parseInt(currentID));

			if (card != null)
			{
				_bankName.setText(card.getBankName());
				_tailNumber.setText(card.getTailNumber());
				_accountsDay.setDate(card.getAccountsDay());
				_repaymentDay.setDate(card.getRepaymentDay());
				_phoneNumber.setText(card.getPhoneNumber());
			}
		}
	}
}